//
//  MyloginViewController.m
//  parent
//
//  Created by yanzhen on 15/7/21.
//  Copyright (c) 2015年 ci123. All rights reserved.
//

#import "MyloginViewController.h"
#import "PopUIManager.h"
#import "ASIFormDataRequest.h"
#import "AppDelegate.h"
#import "SBJsonParser.h"
#import "Tool.h"
#import "Config.h"
#import "UMSocial.h"
#import "MyregisterViewController.h"
#import "ForgetPwdOneViewController.h"

static MyloginViewController *controller = nil;

@interface MyloginViewController ()
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@property (weak, nonatomic) IBOutlet UITextField *phoneNum;
@property (weak, nonatomic) IBOutlet UITextField *pwd;
@property (strong, nonatomic) ASIFormDataRequest *request;
@end

@implementation MyloginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self createTopBar];
}

+ (instancetype)shareController
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        controller = [[self alloc] init];
    });
    
    return controller;
}

-(void)createTopBar
{
    UIBarButtonItem *leftItem =[[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"窗口"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(closeIt:)];
    
    self.navigationItem.leftBarButtonItem = leftItem;
    self.navigationItem.title = @"登录";
    
    UIBarButtonItem *rightItem =[[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"忘记密码"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(forgetPwd:)];
    self.navigationItem.rightBarButtonItem = rightItem;
    _loginBtn.layer.cornerRadius = 5.0;
}
-(void)closeIt:(id)sender
{
    [self.navigationController dismissViewControllerAnimated:YES completion:^{
        
    }];
}

-(void)forgetPwd:(id)sender
{
    ForgetPwdOneViewController *one = [[ForgetPwdOneViewController alloc]init];
    [self.navigationController pushViewController:one animated:YES];
}

- (IBAction)login:(id)sender {
    [self.view endEditing:YES];   //关闭键盘
    debugLog(@"开始登陆");
    PopUIManager *popUIMgr = [PopUIManager getInstanse];
    
    if (_phoneNum.text.length == 0||_pwd.text.length == 0){
        [popUIMgr popAlertView:self title:@"提示" message:@"账户或者密码不能为空" cancelButtonTitle:@"确定"];
        return;
    }
    
    
    NSString *account = _phoneNum.text;
    NSString *psw = _pwd.text;
    
    [popUIMgr showWaitingUI:self.view];
    NSString *add_society_url = [NSString stringWithFormat:@"%@%@",SERVER_URL_NEW,kPhoneLogin];
    NSUserDefaults *standard = [NSUserDefaults standardUserDefaults];
    float longitude = [standard floatForKey:MMLastLongitude];
    float latitude = [standard floatForKey:MMLastLatitude];
    NSString *address = [standard objectForKey:MMLastAddress];
    self.request = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:add_society_url]];
    [self.request setUseCookiePersistence:YES];
    [self.request setPostValue:account forKey:@"phone_num"];
    [self.request setPostValue:psw forKey:@"password"];
    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    NSString *device_token = delegate.deviceToken;
    [self.request setPostValue:device_token forKey:@"device_token"];
    [_request setPostValue:@(longitude) forKey:@"longitude"];
    [_request setPostValue:@(latitude) forKey:@"latitude"];
    [_request setPostValue:address forKey:@"real_place"];
    [self.request setDelegate:self];
    [self.request setDidFailSelector:@selector(requestFailed:)];
    [self.request setDidFinishSelector:@selector(requestFinished:)];
    [self.request startAsynchronous];
}
-(void) requestFailed:(ASIHTTPRequest *) request
{
    [[PopUIManager getInstanse]removeWaitingUI];
    if(request.hud){
        [request.hud hide:YES];
    }
}

-(void) requestFinished:(ASIHTTPRequest *) request
{
    debugLog(request.responseString);
    if(request.hud){
        [request.hud hide:YES];
    }
    [[PopUIManager getInstanse]removeWaitingUI];
    NSString *result  = request.responseString;
    SBJsonParser *parser = [SBJsonParser new];
    NSDictionary *result_info = [parser objectWithString:result];
    NSUInteger code = [Tool defaultIntFromDic:result_info withKey:@"code"];
    if(code > 0 )
    {
        //登陆成功
        NSUInteger user_id = [Tool defaultIntFromDic:result_info withKey:@"result"];
        [[Config Instance] saveUID:user_id];
        [self loginWithUsername:[NSString stringWithFormat:@"%d",user_id] password:@"zhy611"];
        debugLog(@"uid:%d\n",user_id);
       
        [Config Instance].isLogin = YES;
        [[Config Instance] saveCookie:YES];
        [Tool reSetInfo];
        [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(loginSucc:) userInfo:nil repeats:NO];
    }else{
        [Tool showSystemAlert:nil andMsg:@"电话号码不存在或密码错误！"];
    }
}
//点击登陆后的操作
- (void)loginWithUsername:(NSString *)username password:(NSString *)password
{
    //[self showHudInView:self.view hint:NSLocalizedString(@"login.ongoing", @"Is Login...")];
    //异步登陆账号
    [[EaseMob sharedInstance].chatManager asyncLoginWithUsername:username
                                                        password:password
                                                      completion:
     ^(NSDictionary *loginInfo, EMError *error) {
         [self hideHud2];
         if (loginInfo && !error) {
             //设置是否自动登录
             [[EaseMob sharedInstance].chatManager setIsAutoLoginEnabled:YES];
             
             // 旧数据转换 (如果您的sdk是由2.1.2版本升级过来的，需要家这句话)
             [[EaseMob sharedInstance].chatManager importDataToNewDatabase];
             //获取数据库中数据
             [[EaseMob sharedInstance].chatManager loadDataFromDatabase];
             
             //获取群组列表
             [[EaseMob sharedInstance].chatManager asyncFetchMyGroupsList];
             
             //发送自动登陆状态通知
             [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@YES];
             //保存最近一次登录用户名
         }
         else
         {
             switch (error.errorCode)
             {
                 case EMErrorNotFound:
                     TTAlertNoTitle(error.description);
                     break;
                 case EMErrorNetworkNotConnected:
                     TTAlertNoTitle(NSLocalizedString(@"error.connectNetworkFail", @"No network connection!"));
                     break;
                 case EMErrorServerNotReachable:
                     TTAlertNoTitle(NSLocalizedString(@"error.connectServerFail", @"Connect to the server failed!"));
                     break;
                 case EMErrorServerAuthenticationFailure:
                     TTAlertNoTitle(error.description);
                     break;
                 case EMErrorServerTimeout:
                     TTAlertNoTitle(NSLocalizedString(@"error.connectServerTimeout", @"Connect to the server timed out!"));
                     break;
                 default:
                     TTAlertNoTitle(NSLocalizedString(@"login.fail", @"Login failure"));
                     break;
             }
         }
     } onQueue:nil];
}
-(void) loginSucc: (NSTimer *) timer
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (IBAction)weixin:(id)sender {
    
}

- (IBAction)qq:(id)sender {
    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToQQ];
    
    snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
        if (response.responseCode == UMSResponseCodeSuccess) {
            
            UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:UMShareToQQ];
            
            NSLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);
            
        }});
}

- (IBAction)registerMe:(id)sender {
    MyregisterViewController *registerView = [[MyregisterViewController alloc]init];
    [self.navigationController pushViewController:registerView animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
